package juc.utils.semaphore;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreExample2 {

    public static void main(String[] args) throws InterruptedException {
        final Semaphore semaphore = new Semaphore(2);

        for (int i = 0; i < 3; i++) {
            new Thread() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + " in");
                    try {
                        //获取信号量，会抛出可中断异常
                        semaphore.acquire();
                        System.out.println(Thread.currentThread().getName() + " get the semaphore");
                        TimeUnit.SECONDS.sleep(4);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        semaphore.release();
                    }
                    System.out.println(Thread.currentThread().getName() + " out");
                }
            }.start();

            while (true) {
                //可用的许可数
                System.out.println("availablePermits " + semaphore.availablePermits());
                //被block住的线程数，是一个评估值
                System.out.println("QueueLength " + semaphore.getQueueLength());
                TimeUnit.SECONDS.sleep(1);
            }
        }
    }
}
